#!/usr/bin/env node

const axios = require('axios');

// 配置
const BASE_URL = 'http://localhost:3000';
const TEST_COOKIES = 'session=test123; user=testuser; unb=123456789';

// 颜色输出
const colors = {
    reset: '\x1b[0m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    red: '\x1b[31m',
    cyan: '\x1b[36m',
    blue: '\x1b[34m'
};

function log(message, color = 'reset') {
    console.log(`${colors[color]}${message}${colors.reset}`);
}

function logSection(title) {
    console.log(`\n${colors.cyan}${'='.repeat(50)}`);
    console.log(`${title}`);
    console.log(`${'='.repeat(50)}${colors.reset}`);
}

function logTest(name, result, details = '') {
    const status = result ? '✅ PASS' : '❌ FAIL';
    const color = result ? 'green' : 'red';
    log(`${status} ${name}`, color);
    if (details) {
        log(`   ${details}`, 'yellow');
    }
}

// 测试健康检查接口
async function testHealthCheck() {
    logSection('🏥 测试健康检查接口');
    
    try {
        const response = await axios.get(`${BASE_URL}/health`);
        const data = response.data;
        
        logTest('健康检查 - 状态码', response.status === 200, `状态码: ${response.status}`);
        logTest('健康检查 - 响应格式', data.status === 'ok', `响应: ${JSON.stringify(data)}`);
        logTest('健康检查 - 时间戳', data.timestamp, `时间戳: ${data.timestamp}`);
        
    } catch (error) {
        logTest('健康检查', false, `错误: ${error.message}`);
    }
}

// 测试获取令牌接口
async function testTokenAPI() {
    logSection('🔑 测试获取令牌接口');
    
    try {
        const payload = {
            cookies: TEST_COOKIES,
            deviceId: 'test-device-123'
        };
        
        const response = await axios.post(`${BASE_URL}/api/token`, payload);
        const data = response.data;
        
        logTest('获取令牌 - 状态码', response.status === 200, `状态码: ${response.status}`);
        logTest('获取令牌 - 响应格式', data.success === true, `响应: ${JSON.stringify(data)}`);
        
    } catch (error) {
        if (error.response) {
            logTest('获取令牌 - 服务器响应', false, `状态码: ${error.response.status}, 响应: ${JSON.stringify(error.response.data)}`);
        } else {
            logTest('获取令牌', false, `错误: ${error.message}`);
        }
    }
}

// 测试API请求接口
async function testRequestAPI() {
    logSection('📡 测试API请求接口');
    
    try {
        const payload = {
            endpoint: '/test/endpoint',
            data: { test: 'data', timestamp: Date.now() },
            cookies: TEST_COOKIES,
            options: {}
        };
        
        const response = await axios.post(`${BASE_URL}/api/request`, payload);
        const data = response.data;
        
        logTest('API请求 - 状态码', response.status === 200, `状态码: ${response.status}`);
        logTest('API请求 - 响应格式', data.success === true, `响应: ${JSON.stringify(data)}`);
        
    } catch (error) {
        if (error.response) {
            logTest('API请求 - 服务器响应', false, `状态码: ${error.response.status}, 响应: ${JSON.stringify(error.response.data)}`);
        } else {
            logTest('API请求', false, `错误: ${error.message}`);
        }
    }
}

// 测试WebSocket连接接口
async function testWebSocketAPI() {
    logSection('🔌 测试WebSocket连接接口');
    
    try {
        const payload = {
            cookies: TEST_COOKIES,
            connectionId: 'test-connection-123'
        };
        
        const response = await axios.post(`${BASE_URL}/api/websocket/connect`, payload);
        const data = response.data;
        
        logTest('WebSocket连接 - 状态码', response.status === 200, `状态码: ${response.status}`);
        logTest('WebSocket连接 - 响应格式', data.success === true, `响应: ${JSON.stringify(data)}`);
        logTest('WebSocket连接 - 连接ID', data.connectionId, `连接ID: ${data.connectionId}`);
        
        // 测试发送消息
        await testWebSocketSend(data.connectionId);
        
        // 测试关闭连接
        await testWebSocketClose(data.connectionId);
        
    } catch (error) {
        if (error.response) {
            logTest('WebSocket连接 - 服务器响应', false, `状态码: ${error.response.status}, 响应: ${JSON.stringify(error.response.data)}`);
        } else {
            logTest('WebSocket连接', false, `错误: ${error.message}`);
        }
    }
}

// 测试WebSocket发送消息
async function testWebSocketSend(connectionId) {
    try {
        const payload = {
            connectionId: connectionId,
            message: { type: 'text', content: 'Hello from test client!' }
        };
        
        const response = await axios.post(`${BASE_URL}/api/websocket/send`, payload);
        const data = response.data;
        
        logTest('WebSocket发送消息', data.success === true, `响应: ${JSON.stringify(data)}`);
        
    } catch (error) {
        logTest('WebSocket发送消息', false, `错误: ${error.message}`);
    }
}

// 测试WebSocket关闭连接
async function testWebSocketClose(connectionId) {
    try {
        const response = await axios.delete(`${BASE_URL}/api/websocket/connect/${connectionId}`);
        const data = response.data;
        
        logTest('WebSocket关闭连接', data.success === true, `响应: ${JSON.stringify(data)}`);
        
    } catch (error) {
        logTest('WebSocket关闭连接', false, `错误: ${error.message}`);
    }
}

// 测试获取连接列表接口
async function testConnectionsAPI() {
    logSection('📋 测试获取连接列表接口');
    
    try {
        const response = await axios.get(`${BASE_URL}/api/websocket/connections`);
        const data = response.data;
        
        logTest('获取连接列表 - 状态码', response.status === 200, `状态码: ${response.status}`);
        logTest('获取连接列表 - 响应格式', data.success === true, `响应: ${JSON.stringify(data)}`);
        logTest('获取连接列表 - 连接数量', typeof data.data.count === 'number', `连接数量: ${data.data.count}`);
        
    } catch (error) {
        if (error.response) {
            logTest('获取连接列表 - 服务器响应', false, `状态码: ${error.response.status}, 响应: ${JSON.stringify(error.response.data)}`);
        } else {
            logTest('获取连接列表', false, `错误: ${error.message}`);
        }
    }
}

// 测试404接口
async function test404API() {
    logSection('❌ 测试404接口');
    
    try {
        const response = await axios.get(`${BASE_URL}/nonexistent`);
        logTest('404接口', false, '不应该返回200状态码');
        
    } catch (error) {
        if (error.response && error.response.status === 404) {
            logTest('404接口', true, '正确返回404状态码');
        } else {
            logTest('404接口', false, `错误: ${error.message}`);
        }
    }
}

// 主测试函数
async function runAPITests() {
    log(`${colors.cyan}🚀 开始运行闲鱼API接口测试${colors.reset}\n`);
    log(`📍 测试目标: ${BASE_URL}`, 'blue');
    log(`🍪 测试Cookie: ${TEST_COOKIES}`, 'blue');
    
    try {
        // 运行所有API测试
        await testHealthCheck();
        await testTokenAPI();
        await testRequestAPI();
        await testWebSocketAPI();
        await testConnectionsAPI();
        await test404API();
        
        logSection('📊 API测试完成');
        log('所有API测试已完成！如果有失败的测试，请检查服务器是否正常运行。', 'green');
        
    } catch (error) {
        log(`❌ API测试过程中发生错误: ${error.message}`, 'red');
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    runAPITests();
}

module.exports = {
    runAPITests,
    testHealthCheck,
    testTokenAPI,
    testRequestAPI,
    testWebSocketAPI,
    testConnectionsAPI,
    test404API
};
